package com.gxa.gateway.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gxa.gateway.service.AuthenticationService;
import com.gxa.gateway.util.JwtUtil;
import dto.ResultDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import param.AuthParam;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

@Component
@Slf4j
public class AuthGlobalFilter implements GlobalFilter , Ordered {

    @Resource
    private AuthenticationService authenticationService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        try {
//            HttpHeaders headers = exchange.getRequest().getHeaders();
//            List<String> authorization = headers.get("Authorization");
//            ServerHttpResponse response = exchange.getResponse();
//            URI uri = exchange.getRequest().getURI();
//            String path = uri.getPath();
//            int fromIndex = getFromIndex(path, "/", 2);
//            path = path.substring(fromIndex);
//            System.out.println(path);
//            if(path.equals("/login/loginEmail") || path.equals("/login/loginPhone") || path.equals("/login/sendCode") || path.equals("/forget/sendEmail") || path.equals("/forget/password") || path.equals("/token/refreshToken") || path.equals("/login/logout")){
//                System.out.println(1);
//                return chain.filter(exchange);
//            }
//
//            if (authorization == null){
//                ResultDTO res = new ResultDTO(401, "token不能为空！");
//                return change(response,res);
//            }
//
//            String token = authorization.get(0);
//            Integer userId = JwtUtil.getUserId(authorization.get(0));
//            Boolean verfy = JwtUtil.verfy(token, userId);
//            System.out.println(!verfy);
//            if(!verfy){
//                System.out.println(1);
//                ResultDTO res = new ResultDTO(401, "token已过期");
//                return change(response,res);
//            }
//
//            AuthParam authParam = new AuthParam();
//            authParam.setToken(token);
//            authParam.setUri(path);
//            System.out.println(authParam);
//            ResultDTO res = authenticationService.authentication(authParam);
//            System.out.println(res.getCode());
//            System.out.println(res.getCode() != 200);
//            if (res.getCode() != 200) {
//                return change(response,res);
//            }
//        } catch (JsonProcessingException e) {
//            e.printStackTrace();
//        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

    private Mono<Void> change(ServerHttpResponse response, ResultDTO res) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        String resStr = objectMapper.writeValueAsString(res);
        // 设置响应头
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        // 转换buffer
        DataBuffer wrap = response.bufferFactory().wrap(resStr.getBytes());
        return response.writeWith(Mono.just(wrap));
    }

    private int getFromIndex(String str, String modelStr, Integer count) {
        Integer index = 0;
        for (int i = 0; i < str.length() ; i++) {
            if(String.valueOf(str.charAt(i)).equals("/")){
                if(index == count-1){
                    return i;
                }
                index++;
            }

        }
        return 0;
    }
}
